package org.topteam.oschat.message;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

import com.alibaba.fastjson.JSON;

public abstract class JsonCoder<T> implements Encoder.TextStream<T>,
		Decoder.TextStream<T> {

	private Class<T> _type;

	@Override
	public void destroy() {

	}

	@SuppressWarnings("unchecked")
	@Override
	public void init(EndpointConfig endpointConfig) {
		ParameterizedType $thisClass = (ParameterizedType) this.getClass()
				.getGenericSuperclass();
		Type $T = $thisClass.getActualTypeArguments()[0];
		if ($T instanceof Class) {
			_type = (Class<T>) $T;
		} else if ($T instanceof ParameterizedType) {
			_type = (Class<T>) ((ParameterizedType) $T).getRawType();
		}
	}

	@Override
	public T decode(Reader reader) throws DecodeException, IOException {
		BufferedReader br = new BufferedReader(reader);
		StringBuilder sb = new StringBuilder();
		String str;
		while ((str = br.readLine()) != null) {
			sb.append(str);
		}
		return JSON.parseObject(sb.toString(), _type);
	}

	@Override
	public void encode(T object, Writer writer) throws EncodeException,
			IOException {
		String json = JSON.toJSONString(object);
		writer.append(json);
	}

}
